<?php
App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 */
class UsersController extends AppController {


/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->User->read(null, $id);
		}
		$customers = $this->User->Customer->find('list');
		$this->set(compact('customers'));
	}


	
	function login()
	{
		if ($this->request->is('post')) {
	        if ($this->Auth->login()) {
	        	
	        	
	        	//Extract and store associated customer ids for this user
	        			
				$this->loadModel('CustomersUser');
				$custids = $this->CustomersUser->find('all', array(
					'conditions' => array(
						'user_id' => $this->Session->read('Auth.User.id')
					),
					'fields' => array(
						'customer_id'
					)
				));
				
				$custids = Set::Extract('/CustomersUser/customer_id',$custids);
	        	$this->Session->write('Auth.User.customer_ids', $custids);
	        	
	            return $this->redirect($this->Auth->redirect());
	        } else {
	            $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
	        }
	    }			
	}
	
	function logout()
	{
		 $this->redirect($this->Auth->logout());
	}
	
	function dashboard()
	{
		//$_SESSION['Auth']['User']['id'] = 1;
		$this->Session->write('Auth.User.id',1);

		$this->redirect('/accounts/summary');
	}
	
}
